package ex13.pyrmont.startup;

//Use engine
import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleListener;
import org.apache.catalina.connector.http.HttpConnector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.core.StandardWrapper;
import org.apache.catalina.loader.WebappLoader;

import ex13.pyrmont.core.SimpleContextConfig;

public final class Bootstrap2 {
	public static void main(String[] args) {
		// invoke: http://localhost:8080/app1/Primitive or
		// http://localhost:8080/app1/Modern
		System.setProperty("catalina.base", System.getProperty("user.dir"));
		HttpConnector connector = new HttpConnector();

		StandardWrapper wrapper1 = new StandardWrapper();
		wrapper1.setName("Primitive");
		wrapper1.setServletClass("PrimitiveServlet");
		StandardWrapper wrapper2 = new StandardWrapper();
		wrapper2.setName("Modern");
		wrapper2.setServletClass("ModernServlet");

		StandardContext context = new StandardContext();
		// StandardContext's start method adds a default mapper
		context.setPath("/app1");
		context.setDocBase("myApp");

		context.addChild(wrapper1);
		context.addChild(wrapper2);

		LifecycleListener listener = new SimpleContextConfig();
		((Lifecycle) context).addLifecycleListener(listener);

		StandardHost host = new StandardHost();
		host.addChild(context);
		host.setName("localhost");
		host.setAppBase("WebRoot");

		WebappLoader loader = new WebappLoader();
		context.setLoader(loader);
		// context.addServletMapping(pattern, name);
		context.addServletMapping("/Primitive", "Primitive");
		context.addServletMapping("/Modern", "Modern");

		StandardEngine engine = new StandardEngine();
		engine.addChild(host);
		engine.setDefaultHost("localhost");

		connector.setContainer(engine);
		try {
			connector.initialize();
			(connector).start();
			(engine).start();

			// make the application wait until we press a key.
			System.in.read();
			((Lifecycle) engine).stop();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}